<template>
  <div class="dictSetting">
    <div class="top">
      <search-bar v-model="searchModel" :search-data="searchData" :config="searchData" @search="handleSearchSubmit"
        @searchReset="handleSearchReset" style="margin-top:0;margin-left:-20px;padding-top:.2rem">
      </search-bar>
    </div>

    <div class="bottom">
      <div class="btn_area">
        <el-button type="primary" size="medium" @click="add"
        v-hasPermi="['system.dict.add']"
         >添加</el-button>
      </div>

      <LPTablePage :show-index="false" :table-data="tableData" :table-column="tableColumn" :total="total"
        :current-page="currentPage" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"
        ref="tablePage" class="tablePage">
        <template slot="system">
          CRM
        </template>
        <template slot="icon" slot-scope="{ row }">
          <div class="icon-box" @click="changeStar(row)">
            <i :class="['icon', row.isCollection ? 'redStar' : 'star']"></i>
          </div>
        </template>
        <template slot="systemType" slot-scope="{ row }">
        
         <span>{{ row.systemType==1?'CRM':'劳保'  }}</span>
        
        </template>
        <template slot="status" slot-scope="{ row }">
        
        <span>{{ row.status==1?'生效':'失效'  }}</span>
       
       </template>
      </LPTablePage>
    </div>


    <!-- 新增字典 -->
    <base-dialog :visible="addVisile" :title="(isEdit ? '编辑' : '新增') + '字典'" width="918px" class="addDictDialog"
      @handleDialogSubmit="handleAddSubmit" @handleDialogCancle="handleAddCancle">
      <el-form ref="dictForm" :model="dictModel" :rules="dictRule" label-width="120px" class="dictForm"
        label-position="top" size="medium">
        <el-row :gutter="50">
          <el-col :span="12">
            <el-form-item label="所属系统组织:" prop="systemType">
          <el-select v-model="dictModel.systemType" placeholder="所属系统组织" filterable 
                          >
                          <el-option
                          v-for="(item, index) in systemOptions"
                          :key="index"
                          :value="item.value"
                          :label="item.label"
                          />
                          </el-select> 
              <!-- <el-input  v-model="dictModel.system" readonly></el-input> -->
              
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典码:" prop="dictCode">
              <el-input v-model.trim="dictModel.dictCode" placeholder="请输入">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典名称:" prop="dictValue">
              <el-input v-model.trim="dictModel.dictValue" placeholder="请输入">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典描述:" prop="remark">
              <el-input v-model="dictModel.remark" placeholder="请输入">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态:" prop="status">
          
              <el-radio-group v-model="dictModel.status" >
              <el-radio v-for="radio in statusOptions" :key="radio.label" :label="radio.value">{{
                radio.label
              }}</el-radio>
            </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 字典明细 -->
        <el-row>
          <div class="dictDetail">字典明细
            <el-button type="text" icon="el-icon-plus" @click="appendChild" class="appendChild">添加</el-button>
          </div>
          <el-tree :data="dictModel.sysDictDataDetailList" node-key="uid" :default-expand-all="true" :expand-on-click-node="false"
          :props="defaultProps"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <!-- <span>{{node.label}}</span> -->
              <span class="ipt-box">
                <el-form-item class="sort" label-width="0px" prop="dictSort" :rules="[
                  { trigger: ['blur'], validator: (rule, value, callback) => { validateRepeat(rule, value, callback, data, node) } },
                ]">
                  <el-input placeholder="序号" v-model="data.dictSort" clearable class="sortIpt" size="medium" />
                </el-form-item>

                <el-form-item label-width="0px" prop="dictValue" :rules="[
                  { trigger: 'blur', validator: (rule, value, callback) => { validateEmpty(rule, value, callback, data) } },
                ]">
                  <el-input placeholder="字典项" v-model="data.dictValue" clearable size="medium" />
                </el-form-item>
              </span>

              <span class="btn">
                <el-button type="text" size="mini" @click="() => append(data)">
                  添加子级
                </el-button>
                <el-button type="text" size="mini" @click="() => remove(node, data)" class="deleteBtn">
                  删除
                </el-button>
              </span>

            </span>
          </el-tree>
        </el-row>
      </el-form>
    </base-dialog>
  </div>
</template>

<script>
import {getDictList,
addDict,
editDict,
deleteDict,
getDictDetail
} from '@/api/system/dictSetting' 
import {validateNumber} from '@/utils/validate'
import TablePage from '@/components/TablePage'
import LPTablePage from '@/components/LPTablePage'
import SearchBar from '@/components/SearchBar'
import baseDialog from '@/components/BaseDialog'

export default {
  name: "DICTSETTING",
  components: {
    SearchBar, LPTablePage, baseDialog
  },
  data() {
    return {
      searchModel: {

      },
      defaultProps:{
        children:'sysDictDataDetailList'
      },
      statusOptions:[
      { label: '生效', value: '1' },
            { label: '失效', value: '2' },
           
      ],
      searchData: [
        { placeholder: "字典名称", prop: "dictValue" },
        {
          prop: 'status',
          type: 'select',
          placeholder: '状态',
          options: [
            { label: '生效', value: '1' },
            { label: '失效', value: '2' },
            { label: '全部', value: '0' }
          ]
        },
        {
          prop: 'systemType',
          type: 'select',
          placeholder: '所属系统',
          options: [
            { label: 'CRM', value: '1' },
            { label: '劳保', value: '2' }
          ]
        },
        {
          prop: 'search',
          type: 'button',
        policy: ['system.dict.query'], 
        }, 

      ],
      tableColumn: [
        { label: "系统组织", prop: "systemType", render: true },
        { label: "字典码", prop: "dictCode" },
        { label: "状态", prop: "status", render: true  },

        { label: "字典名称", prop: "dictValue" },
        { label: "备注", prop: "remark" },
        // { label: "创建人", prop: "creator" },
        { label: "创建时间", prop: "createTime" },
        {
          label: "操作",
          prop: "action",
          type: "button",
          hideTooLtip: true,
          buttons: [
            {
              label: "编辑",
              type: "text",
              icon: "el-icon-view",
              method: `_edit${this.$options.name}`,
              policy: ['system.dict.edit'],
              // policy: 'system.dict.edit',

            
            },
            {
              label: "删除",
              type: "text",
              icon: "el-icon-view",
              class: "deleteBtn",
              method: `_delete${this.$options.name}`,
            policy: ['system.dict.remove'],
            // policy:'system.dict.remove'

          
            },
          ]
        }
      ],
      tableData: [],
      total: 0,
      currentPage: 1,
      addVisile: false,
      isEdit: false,
      dictModel: {
        dictCode:'',
        dictValue:'',
        systemType:'',
        // items: [],
        status:'',
        
        remark:'',
        sysDictDataDetailList:[]
        // sysDictDataDetailList:[
        // {
        //   dictSort:'',
        //   dictValue:'',
        //   sysDictDataDetailList:[
         
        //   ]
        // }
        // ],
      },
      treeColumn: [
        { label: "序号", prop: "index" },
        {
          label: "字典项", prop: "label", render: true,
          // hideTooLtip: true,
          // customeHeader:true,
          // headerSlot:'labelHeader',
          width: 170
        },
        {
          label: "操作",
          prop: "action",
          type: "button",
          button: [
            {
              label: "添加子级",
              type: "text",
              icon: "el-icon-view",
              method: `_add${this.$options.name}`,
            },
            {
              label: "删除",
              type: "text",
              icon: "el-icon-view",
              method: `_delete${this.$options.name}`,
            },
          ]
        }
      ],
      dictRule: {
        dictCode:[{ required: true, trigger: "blur", message: "必填" }],
        dictValue: [{ required: true, trigger: "blur", message: "必填" }],
      },
      systemOptions: [
        { value: 1, label: 'CRM' },
        { value:2, label: '劳保' },
        
      ],
    }
  },
  mounted() {
    this.getDictList()
    this.handTableEvents();
  
  },
  methods: {
    getDictList() {
      let { pageSize } = this.$refs.tablePage;
      let params = {
        ...this.searchModel,
        pageSize: pageSize,
        pageNum: this.currentPage
        // pageNum: (this.currentPage - 1) * pageSize,
        // pageNum:this.currentPage
        // currentPage
      }
      getDictList(params).then(res => {
          console.log('getDictList',res);
        this.tableData = res.rows;
        this.total = res.total
      })
    },
    findTreeIndex(id) {

    },
    handTableEvents() {
      this.$bus.$on(`_edit${this.$options.name}`, (row) => {
        console.log("编辑", row);
        //  this.dictModel
        getDictDetail({ dictId: row.id }).then(res => {
          if (!res.error) {
            console.log('getDictDetailByName', res);
            
            this.dictModel = { ...row, status:row.status.toString(),sysDictDataDetailList: res.data.sysDictDataDetailList }
            this.isEdit = true;
            this.addVisile = true;
          }
        })
      });
      this.$bus.$on(`_delete${this.$options.name}`, (row) => {
        console.log("删除", row);
        this.$confirm('确定删除吗', '删除', {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          closeOnClickModal: false
        }).then(() => {
          console.log('确认');
          deleteDict(row.id).then(res => {
            if (!res.error) {
              this.$message.success("删除成功")
              this.getDictList()
            }
          })
        })
      });
    },
    handleSearchSubmit() {
      this.currentPage = 1;
      this.getDictList()
    },
    handleSearchReset() {
      this.currentPage = 1;
      this.getDictList()
    },
    handleSizeChange(v) {
      this.pageSize = v;
      this.currentPage = 1;
      this.getDictList()
    },
    handleCurrentChange(v) {
      this.currentPage = v;
      this.getDictList()
    },
    add() {
      this.isEdit = false;
      this.addVisile = true;
    },
    handleAddSubmit() {
      // this.addVisile = false;
      this.$refs.dictForm.validate(valid => {
        if (valid) {
          console.log('handleAddSubmit 验证通过', this.dictModel);
          if (!this.isEdit) {
            addDict(this.dictModel).then(res => {
      
              if (res.code==200) {
                console.log('addDict', res);
                this.addVisile = false;
                this.dictModel = this.$options.data().dictModel

                this.$message.success("添加字典成功")
               
                this.getDictList()
              }
            })
          } else {
            editDict(this.dictModel).then(res => {
              if (res.code==200) {
                console.log('editDict', res);
                this.addVisile = false;
                this.dictModel = this.$options.data().dictModel
                this.$message.success("编辑字典成功")
               
                this.getDictList()
              }
            })
          }
        } else {
          this.$message.warning("请检查字典信息")
          return false
        }
      })
    },
    handleAddCancle() {
      this.dictModel = {
        sysDictDataDetailList: []
      }
      this.resetForm("dictForm")
      this.addVisile = false;
    },
    validateEmpty(rule, value, callback, data) {
      // console.log('validateEmpty', data);
      //  callback()
      if (!data.dictValue || data.dictValue == undefined) {
        return callback(new Error('请输入'))
      } else {
        callback()
      }
    },
    validateRepeat(rule, value, callback, data, node) {
      //   console.log('validateRepeat',data);
      if (!data.dictSort) {
        return callback()
      }
      if (!validateNumber(data.dictSort)) {
        return callback(new Error("请输入正确数字"));
      } else {
        let siblings = node.parent.childNodes;
        for (let item of siblings) {
          if (item.data.dictSort == data.dictSort && (item.data.id != data.id || item.data.uid != data.uid)) {
            return callback(new Error("序号重复"));
          }
        }
        return callback()
      }
    },
    appendChild() {
      this.dictModel.sysDictDataDetailList.push(
        { uid: new Date().getTime(), dictValue: null, sysDictDataDetailList: [] }
      )
    },
    append(data) {
      const newChild = { uid: new Date().getTime(), dictValue: null, sysDictDataDetailList: [] };
      if (!data.sysDictDataDetailList) {
        this.$set(data, 'sysDictDataDetailList', []);
      }
      data.sysDictDataDetailList.push(newChild);
    },
   
    remove(node, data) {
      const parent = node.parent;
      const sysDictDataDetailList = parent.data.sysDictDataDetailList || parent.data;
      const index = sysDictDataDetailList.findIndex(d => {
        if (d.uid) {
          return d.uid === data.uid
        } else {
          return d.id === data.id
        }
      });
      sysDictDataDetailList.splice(index, 1);
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  }
}
</script>

<style lang="scss" scoped>
.dictSetting {

  //padding: 0 .2rem .2rem;
  .top {
    background-color: #fff;
    padding: 0 .3rem;
  }

  .bottom {
    .btn_area {
      margin-bottom: .2rem;
      margin-left: .3rem;
    }

    background-color: #fff;
    margin-top: .2rem;
    padding: .2rem 0rem;

  }

  .addDictDialog {
    .dictForm {
      // padding-right: .2rem;
    }

    ::v-deep .el-select {
      width: 100%;
    }

    .dictDetail {
      padding-left: .1rem;
      font-size: 14px;
      font-weight: bold;
      margin-bottom: .1rem;

      .appendChild {
        margin-left: .2rem;
      }
    }

    .el-tree {
      background-color: #F6F6F6;
      padding-top: .1rem;
    }
  }

  ::v-deep .el-tree-node__content {
    // height: 58px;
    height: 70px;
  }

  .custom-tree-node {
    width: 100%;
    display: flex;
    align-items: center;

    // justify-content: space-between;
    .ipt-box {
      display: flex;
      align-items: center;

      .sort {
        margin-right: 9px;
      }
    }

    font-size: 14px;

    // padding-bottom: .1rem;
    .el-form-item {
      margin: 0;

      .el-form-item__content {
        margin-left: 0;
      }
    }

    .btn {
      margin-left: .46rem;

      .deleteBtn {
        margin-left: .4rem;
        color: #ee3333;
      }
    }

    .sortIpt {
      width: 76px;
      //    ::v-deep .el-input__inner{
      //         padding: 0;
      //     }
    }
  }

  ::v-deep .tablePage {
    .deleteBtn {
      color: #ee3333;
    }
  }
}
</style>